import 'dart:collection';
import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter_app/store.dart';


class HttpRequest {
  static String _baseUrl = 'http://59.44.43.228:8080';
  static String BASE_IMG_URL = 'http://59.44.43.228';
  // static String _baseUrl = 'http://59.44.43.228:8080';
  static const CONTENT_TYPE_JSON = "application/json";
  static const CONTENT_TYPE_FORM = "application/x-www-form-urlencoded";
  static int timeoutMs = 10000;
  // static Map optionParams = {
  //   "timeoutMs": 10000,
  //   "token": null,
  //   "authorizationCode": null,
  // };

  static get(url, param, { Map<String, String> header }) async{
    return await request(url, param,'GET', header);
  }

  static post(url, param, { Map<String, String> header }) async{
    return await request(url, param, 'POST', header);
  }
  //
  // static delete(url,param) async{
  //   return await request(_baseUrl+url, param, null, new Options(method: 'DELETE'));
  // }
  //
  // static put(url,param) async{
  //   return await request(_baseUrl+url, param, null, new Options(method: "PUT", contentType: ContentType.text));
  // }

  static request(url, params, methods, Map<String, String> header, {noTip = false}) async {
    // print(params);
    //没有网络
    // var connectivityResult = await (new Connectivity().checkConnectivity());
    // if (connectivityResult == ConnectivityResult.none) {
    //   return new ResultData(Code.errorHandleFunction(Code.NETWORK_ERROR, "", noTip), false, Code.NETWORK_ERROR);
    // }

    // 默认请求的header
    var contentTypes = Headers.jsonContentType;
    if(methods == 'POST'){
      contentTypes = Headers.formUrlEncodedContentType;
    }

    // 如果自定义
    Map<String, String> headerDefault = new HashMap();
    headerDefault = {
      HttpHeaders.userAgentHeader: "dio",
      "api": "1.0.0",
    };
    // 加入token
    if(url != '/uaa/auth/code/image' && url != '/uaa/auth/form'){
      User user = new User();
      var token = await user.getUser();
      headerDefault['Authorization'] = 'Bearer $token';
    }
    // 加入默认请求
    if (header != null) {
      if(header['Content-Type'] != null){
        contentTypes = header['Content-Type'];
      }
    }

    Dio dio = Dio(BaseOptions(
      method: methods,
      baseUrl: _baseUrl,
      // 服务器链接超时，毫秒
      connectTimeout: timeoutMs,
      // 响应流上前后两次接受到数据的间隔，毫秒
      receiveTimeout: 3000,
      headers: headerDefault,
      contentType: contentTypes,
      // 文本(字符串)格式接收响应数据，`JSON`, `STREAM`, `PLAIN`(字符串)
      responseType: ResponseType.json,
    ));

    dio.interceptors.add(InterceptorsWrapper(
        onRequest:(RequestOptions options) async {
          // 在请求被发送之前做一些事情
          // 进度条之类的
          return options; //continue
          // 如果你想完成请求并返回一些自定义数据，可以返回一个`Response`对象或返回`dio.resolve(data)`。
          // 这样请求将会被终止，上层then会被调用，then中返回的数据将是你的自定义数据data.
          //
          // 如果你想终止请求并触发一个错误,你可以返回一个`DioError`对象，或返回`dio.reject(errMsg)`，
          // 这样请求将被中止并触发异常，上层catchError会被调用。
        },
        onResponse:(Response response) async {
          // 在返回响应数据之前做一些预处理
          return response; // continue
        },
        onError: (DioError e) async {
          // 当请求失败时做一些预处理
          return e;//continue
        }
    ));

    Response response;
    try {
      // queryParameters,data  根据后台的不同，需要修改
      response = await dio.request(url, queryParameters: params);
    } on DioError catch (e) {
      return e;
    }

    if(response.data == ''){
      return null;
    }

    if(response.data is String) {
      return ResultData.fromJson(json.decode(response.data));
    }
    // 目前确少判断
    return ResultData.fromJson(response.data);
  }

//  图片上传的问题
  static requestPicture(url, data) async {

    User user = new User();
    var token = await user.getUser();
    Map<String, String> headerDefault = new HashMap();
    headerDefault = {
      HttpHeaders.userAgentHeader: "dio",
      "api": "1.0.0",
      'Authorization':'Bearer $token'
    };
    Dio dio = Dio(BaseOptions(
      method: 'POST',
      baseUrl: _baseUrl,
      // 服务器链接超时，毫秒
      connectTimeout: timeoutMs,
      // 响应流上前后两次接受到数据的间隔，毫秒
      receiveTimeout: 3000,
      headers: headerDefault,
      contentType: Headers.jsonContentType,
      // 文本(字符串)格式接收响应数据，`JSON`, `STREAM`, `PLAIN`(字符串)
      responseType: ResponseType.json,
    ));
    Response response;
    try {
      response = await dio.request(url, data: data);
    } on DioError catch (e) {
      print(e);
    }
    print(response);
    return ResultData.fromJson(response.data);
  }
}




///返回对象封装
class ResultData {
  ResultData(this.code, this.msg, this.data);

  //后台返回的错误码
  int code;
  //返回的信息
  String msg;
  //返回的数据，需要自己进行处理成自己想要的对象
  Map<String, dynamic> data;

  ResultData.fromJson(Map<String, dynamic> json)
      :
        code = json["code"],
        msg = json["msg"],
        data = json["data"]!=''?json["data"]:null;
}